#include <webhttpd/Basic.h>

#include <srclink/static_response.h>
#include <srclink/utils.h>


// 资源文件链接，用于发送 html、js、css 等资源文件。
HttpResponse static_response(HttpRequest request) {
    // 获取请求资源路径
    char filepath[BUFFER_SIZE] = "./static/";

    strcat_s(filepath, BUFFER_SIZE, strstr(request.path, "/static/") + 8);

    // 寻找是否有查询字符串
    char * query_string = strstr(filepath, "?");

    if (query_string != NULL) {
        // 忽略查询字符串
        filepath[query_string - filepath] = '\0';
    }

    FILE *file = fopen(filepath, "rb"); // 以二进制模式打开文件
    if (!file) {
        return not_found_response(request);
    }

    // 获取文件大小
    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    fseek(file, 0, SEEK_SET);

    // 读取文件内容到缓冲区
    char *file_content = malloc(file_size);
    fread(file_content, 1, file_size, file);
    fclose(file);

    // 构造响应
    HttpResponse response;
    response.status_code = 200;
    response.headers = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);

    // 设置 MIME 类型
    const char *mime_type = get_mime_type(filepath);
    g_hash_table_insert(response.headers, g_strdup("Content-Type"), g_strdup((char *) mime_type));

    // 设置响应体内容和大小
    response.body.content = file_content;
    response.body.size = file_size;

    return response;
}

// 发送页面模板，这里简单搞搞
HttpResponse send_template(HttpRequest request, char *filepath_) {
    char filepath[BUFFER_SIZE] = "./templates/";

    strcat_s(filepath, BUFFER_SIZE, filepath_);

    FILE *file = fopen(filepath, "rb"); // 以二进制模式打开文件
    if (!file) {
        return not_found_response(request);
    }

    // 获取文件大小
    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    fseek(file, 0, SEEK_SET);

    // 读取文件内容到缓冲区
    char *file_content = malloc(file_size);
    fread(file_content, 1, file_size, file);
    fclose(file);

    // 构造响应
    HttpResponse response;
    response.status_code = 200;
    response.headers = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);

    // 设置 MIME 类型
    const char *mime_type = get_mime_type(filepath);
    g_hash_table_insert(response.headers, g_strdup("Content-Type"), g_strdup((char *) mime_type));

    // 设置响应体内容和大小
    response.body.content = file_content;
    response.body.size = file_size;

    return response;
}